/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;
import java.util.Locale;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.Searcher;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;
import util.Data_variante;
import util.Lucene_Index;
//import .Comment_show;

/**
 *
 * @author dragonboy
 */
public class submit_action extends HttpServlet {

    String [] App={"All","Blog","Photo","Album","Feed","Q&amp;A (Product)","","","","","","","","","","","123Mua (Product)","Mp3-Song (Product)","Mp3-Video (Product)","Mp3-Playlist (Product)","Link","Live"};
    String [] TypeCmt = {"Normal","Unsured Spam","Spam","Bad","Unsure Polictics", "Unsure Common"};
    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    
    
    protected void reload_comment(PrintWriter out,HttpServletRequest request, String indexDateDir, String typeCmt, String type_app, String date_index) throws ParseException, IOException{

        DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        DecimalFormat df = new DecimalFormat("#,###");
        df.setDecimalFormatSymbols(new DecimalFormatSymbols(Locale.ITALIAN));
        int count = 0;
        File file = new File(indexDateDir);
            Searcher searcher
                = new IndexSearcher(FSDirectory.open(file));
            QueryParser parser = new QueryParser(Version.LUCENE_34, "OwnerID", new StandardAnalyzer(Version.LUCENE_34));
            String command = "Type:"+typeCmt+" AND Status:0";
            Query myquery = parser.parse(command);
            int hitsPerPage = 300;
            int pagesize = 10;
            TopDocs results = searcher.search(myquery,300);
            int totalHit = results.totalHits;
            System.out.println("total hits reload: "+ totalHit);
            int nums_gotten = (totalHit > hitsPerPage)? hitsPerPage: totalHit;
            int nums_page = (nums_gotten % pagesize == 0)? (nums_gotten/pagesize): ((nums_gotten/pagesize)+1);
            ScoreDoc[] hits = results.scoreDocs;
            out.println("<script type=\"text/javascript\">"
                    + "function check_checkbox(value,ischecked){"
                    + "document.getElementById(\"table-body\")."
                    + "}"
                    + "</script>");
            out.println("<script type=\"text/javascript\">"
                        +"$(document).ready(function() {"
                        +"$(\"#content-action-table tbody\").quickPager( {"
                        +"pageSize:"+ pagesize+","
                        +"currentPage: 1,"
                        +"holder: \".pagination\""
                        //+"holder:\"\""
                        +"});"
                        +"});"
                       +"</script>");
            int typenum = Integer.valueOf(typeCmt);
            int paranum = Integer.valueOf(type_app);
            out.println("<div id=\"header-tip\"></div>"
                    +"<form name=\"HanderContentComment\" action=\"submit_action\" method=\"POST\" onsubmit=\"xmlhttpPost(\'submit_action\', \'HanderContentComment\', \'content-action\', \'\'); return false;\">"
                    +"Total: " + df.format(totalHit)
                    +"<input type=\"submit\" value=\"" + Data_variante.submit_button_value +"\" name=\"submit["+date_index+"]\" class=\"handersubmit\">"
                    +"<input type=\"hidden\" value=\""+ type_app +"\" name=\"Appcheck["+ type_app +"]\">"
                    +"<input type=\"hidden\" value=\""+ typeCmt +"\" name=\"Typecheck["+ typeCmt +"]\">"
                    + "<br class=\"clear-all\"><br class=\"clear-all\">"
                    +"<table id=\"content-action-table\" cellpadding=\"0\" cellspacing=\"0\">"
                    +"<thead>"
                    +"<tr>"
                    +"<th class=\"table-the-first\">"+ Data_variante.table_col1_name +"</th>"
                    +"<th class=\"table-1\">"+ Data_variante.table_col2_name + "</th>"
                    //+"<th class=\"table-6\">"+ Data_variante.table_col7_name + "</th>"
                    +"<th class=\"table-7\">"+ Data_variante.table_col8_name +"</th>"
                    +"<th class=\"table-2\">"+ Data_variante.table_col3_name + "</th>"
                    +"<th class=\"table-3\">"+ Data_variante.table_col4_name(typeCmt) +"&nbsp;<input type=\"checkbox\" id=\"check_delete_all\" name=\"check_all_delete\" onclick=\"SetSel(this);\" ></th>"
                    +"<th class=\"table-4\">"+ Data_variante.table_col5_name(typeCmt) +"&nbsp;<input type=\"checkbox\" id=\"check_approve_all\" name=\"check_all_approve\" onclick=\"SetSel(this);\"></th>"
                    +"<th class=\"table-5\">"+ Data_variante.table_col6_name + "</th>"
                    +"<th class=\"table-6\">"+ Data_variante.table_col7_name +"</th>"
                    +"</tr>"
                    +"</thead>"
                    +"<tbody id=\"table-body\">");
            Date date;
            count = 0;
            for(ScoreDoc hit : hits) {
                  count++;
                  Document d = searcher.doc(hit.doc);
                  date = new Date(Long.valueOf(d.get("Time"))*1000);
                  out.println("<tr>"
                    + "<td class=\"table-the-first\">"+ count + "</td>"
                    + "<td>" + TypeCmt[typenum] + "</td>"
                    + "<td >"+ d.get("OwnerID") +"</td>"
                    //+ "<td >" + "</td>"
                    + "<td><div class=\"content-action-table-comment\">" + d.get("Comment") +"</div></td>"
                    + "<td><input type=\"radio\" value=\"0\" class=\"check_remove_id\" name=\"check["+ hit.doc +"]\"></td>"
                    + "<td><input type=\"radio\" value=\"1\" class=\"check_approve_id\" name=\"check["+ hit.doc +"]\"></td>"
                    + "<td>" + dateFormat.format(date) + "</td>"
                    + "<td >"+ App[paranum] +"</td>"
                    + "</tr");//style=\"text-align: left;border: 1px solid #AAAAAA;height: 60px;padding: 5px;overflow-y: auto;word-break: break-word;\"
            }
            out.println("</tbody>"
                        +"</table>"
                        //+"<br class=\"clear-all\">"
                        +"<div id=\"delete-all-div\" class=\"deleteall\"><input type=\"checkbox\" id=\"All_delete\" name=\"Delete_all\" onclick=\"SetSel(this);\" >"+ " <b>Delete All</b>" +"</div>"
                        +"<br class=\"clear-all\">"
                        +"</form>"
                        +"<div class=\"pagination\">"
                        //+"</div>"
                        +"</div>");
            out.println("<script type=\"text/javascript\">"
                    + "$(function() {"
                    + "$(\".pagination\").paginate({"
                    + "count                   :"+ nums_page +","
                    + "start                   : 1,"
                    + "display                 : 10,"
                    + "border                  : true,"
                    + "border_color            : '#fff',"
                    + "text_color              : '#fff',"
                    + "background_color        : 'black',"
                    + "border_hover_color      : '#ccc',"
                    + "text_hover_color        : '#000',"
                    + "background_hover_color  : '#fff', "
                    + "images                  : false,"
                    + " mouse                   : 'press',"
                    + "onChange                : function(page){"
                    + "$('._current','#table-body').removeClass('_current').hide();"
                    + "$('.page'+page).addClass('_current').show();}"
                    + "});});"
                    + "</script>");
            out.println("<script type=\"text/javascript\">"
                + "function SetSel(elem){"
                    //+ "var elems = document.getElementsByTagName(\"input\");"
                    + "var name = elem.name;"
                    + "var elems;"
                    + "var elem_checkbox;"
                    + "var elem_checkbox1;"
                    + "if(elem.getAttribute('name') === \"check_all_delete\"){"
                        + "elem_checkbox = $(\"#check_approve_all\",'#content-action-table');"
                        + "elem_checkbox1 = $(\"#All_delete\",'#delete-all-div');"
                        + "elems = $(\"._current :input\",'#table-body');"
                    + "}else if(elem.getAttribute('name') === \"check_all_approve\"){"
                        + "elem_checkbox = $(\"#check_delete_all\",'#content-action-table');"
                        + "elem_checkbox1 = $(\"#All_delete\",'#delete-all-div');"
                        + "elems = $(\"._current :input\",'#table-body');"
                    + "}else{"
                        + "elem_checkbox = $(\"#check_approve_all\",'#content-action-table');"
                        + "elem_checkbox1 = $(\"#check_delete_all\",'#content-action-table');"
                        + "elems = $(\"#table-body :input\");"
                    + "}"
                    + "elem_checkbox[0].checked = false;"
                    + "elem_checkbox1[0].checked = false;"
                    + "var currentState = elem.checked;"
                    + "var elemsLength = elems.length;"
                    + "for(i=0; i<elemsLength; i++){"
                        //+ "if(elems[i].type === \"checkbox\"){"
                        //    + "elems[i].checked = false;  "
                        //+ "}"
                        + "if(elems[i].type === \"radio\"){"
                            + "if((elem.getAttribute('name') === \"check_all_delete\" && elems[i].getAttribute('class') ===\"check_remove_id\")|| (elem.getAttribute('name') === \"check_all_approve\" && elems[i].getAttribute('class') ===\"check_approve_id\")){"  
                                + "elems[i].checked = currentState;"
                            + "}"
                            + "else if(elem.getAttribute('name') === \"Delete_all\" && elems[i].getAttribute('class') ===\"check_remove_id\"){"
                                + "elems[i].checked = currentState;"
                            + "}else{"
                                + "elems[i].checked = false;"
                            + "}"
                        + "}"
                    + "}"
                    + "elem.checked = currentState;"
                + "}"
                + "</script>");
            searcher.close();
             /** 
             */
    }
    
    protected void get_checked_comment(HttpServletRequest request, String indexDateDir) throws IOException{
        File file  = new File(indexDateDir);
        FSDirectory dir = FSDirectory.open(file);
        String name = null;
        int doc_id;
        Enumeration enumAttr =  request.getParameterNames();
        while(enumAttr.hasMoreElements()){
            name = (String)enumAttr.nextElement();
            System.out.println("name is: "+ name + " value is: "+ request.getParameter(name));
            if(name.startsWith("check")){
                IndexReader reader = IndexReader.open(dir, false);
                Document doc = new Document();
                doc_id = Integer.valueOf(name.substring(6,name.length()-1));
                System.out.println("max doc:" + reader.maxDoc());
                Document currDoc = reader.document(doc_id);
                //add field to new doc
                doc.add(new Field("ContentID", currDoc.get("ContentID"),Field.Store.YES, Field.Index.NOT_ANALYZED));
                doc.add(new Field("Time", currDoc.get("Time"), Field.Store.YES, Field.Index.NOT_ANALYZED));
                doc.add(new Field("Type", currDoc.get("Type"), Field.Store.YES, Field.Index.NOT_ANALYZED));
                doc.add(new Field("OwnerID", currDoc.get("OwnerID"), Field.Store.YES, Field.Index.NOT_ANALYZED));
                doc.add(new Field("Comment", currDoc.get("Comment"), Field.Store.YES, Field.Index.ANALYZED));
                doc.add(new Field("AppID", currDoc.get("AppID"), Field.Store.YES, Field.Index.NOT_ANALYZED));
                reader.deleteDocument(doc_id);
                reader.close();
                IndexWriter writer = new IndexWriter(dir,
                    Lucene_Index.getAnalyzer(),
                    IndexWriter.MaxFieldLength.LIMITED);
                if(request.getParameter(name).equals("0")){
                    //delete this doc and add new doc like current doc except "Status" field will "1"
                    doc.add(new Field("Status", "1", Field.Store.YES, Field.Index.NOT_ANALYZED));
                }else{
                    //delete this doc and add new doc like current doc except "Status" field will "1"
                    doc.add(new Field("Status", "2", Field.Store.YES, Field.Index.NOT_ANALYZED));
                }
                writer.addDocument(doc);
                writer.close();
            } 
        }
    }

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        
        Enumeration enumAttr =  request.getParameterNames();
        String name = null;
        String date_index = null;
        String type_app = null;
        String typeCmt = null;
        int count = 0;
        while(enumAttr.hasMoreElements() && count < 3){
            name = (String)enumAttr.nextElement();
            System.out.println("begin reload data: "+ name);
            if(name.startsWith("submit[")){
                System.out.println("name submit: "+ name);
                date_index = name.substring(7,name.length()-1);
                count++;
            }
            else if(name.startsWith("Appcheck[")){
                System.out.println("name appcheck: "+ name);
                type_app = name.substring(9, name.length()-1);
                count++;
            }
            else if(name.startsWith("Typecheck[")){
                System.out.println("name typecheck: "+ name);
                typeCmt = name.substring(10, name.length()-1);
                count++;
            }
        }
        String indexDateDir = Data_variante.dir_index + "/" + date_index;
        get_checked_comment(request, indexDateDir);
        try {
            reload_comment(out, request, indexDateDir, typeCmt, type_app, date_index);
        } catch (ParseException ex) {
            Logger.getLogger(submit_action.class.getName()).log(Level.SEVERE, null, ex);
        }
        finally {            
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
